package com.jielin.handling.util.pdfutil;

import com.amazonaws.services.dynamodbv2.xspec.S;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.parser.PdfContentStreamProcessor;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @Description 去除笔录水印
 * @Author WR
 * @Date 2020-10-14 15:34
 * @Version 1.0
 */
public class RemoveWatermark {

    public static String REMOVEWATERMARKTEXT = "_RemoveWatermark";

    public static void main(String[] args) {
        removeWatermark("C:\\data\\recordpdfs\\万中天的笔录2019_8_9_418566010.pdf", "C:\\data\\recordpdfs\\万中天的笔录2019_8_9_418566010_2.pdf");
    }

    /**
     * 去除水印
     *
     * @param sourceFilePath 源文件路径
     * @param targetFilePath 目标文件路径
     */
    public static void removeWatermark(String sourceFilePath, String targetFilePath) {
        try {
            PdfReader pdfReader = new PdfReader(sourceFilePath);
            FileOutputStream os = new FileOutputStream(targetFilePath);
            PdfStamper stamper = new PdfStamper(pdfReader, os);
            PdfContentStreamEditor editor = new PdfContentStreamEditor() {
                @Override
                protected void write(PdfContentStreamProcessor processor, PdfLiteral operator, List<PdfObject> operands)
                        throws IOException {
                    String operatorString = operator.toString();
                    //Tj 操作通过当前的字体和其他文字相关的图形状态参数来取走一串操作和绘制相应的字形
                    //Tr操作设置的文本渲染模式
                    //一个文本对象开始于BT，结束于ET
                    final List<String> TEXT_SHOWING_OPERATORS = Arrays.asList("Tj", "'", "\\", "TJ");
//                    System.out.println(operatorString);
                    if (TEXT_SHOWING_OPERATORS.contains(operatorString)) {
                        PdfDictionary dic = gs().getFont().getFontDictionary();
//                        System.out.println(gs().getFont().getPostscriptFontName());
//                        if (gs().getFont().getPostscriptFontName().endsWith("BoldMT")) {//BoldMT字体的名称
//                        if (gs().getFont().getPostscriptFontName().endsWith("STSong-Light-UniGB-UCS2-H")) {//BoldMT字体的名称
                        // 根据水印字体大小去除水印
                        if (Watermark.getWatermarkFont().getSize() == gs().getFontSize()) {
                            return;
                        }
                    }
                    super.write(processor, operator, operands);
                }
            };
            for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {
                editor.editPage(stamper, i);
            }
            stamper.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

}
